defmodule Club.Adapter do
    
    alias Club.Repo
    alias Club.SchemaClub
    require Ecto.Query
    require Logger

    def create_club(params) do
        create_club(params, 10)
    end

    def create_club(params, 0) do
        nil
    end

    def create_club(params, count) when is_integer(count) do
        invitecode = SecureRandom.base64(9)

        params = Map.put(params, :invitecode, invitecode)

        changeset = SchemaClub.changeset(%SchemaClub{}, params)

        case changeset.valid? do
            true ->
                case Repo.insert(changeset) do
                    {:ok, club} ->
                        club
                    {:error, msg} ->
                        errormsg = SchemaClub.getErrorMsg(msg.errors, %{})
                        if Map.has_key?(errormsg, :invitecode) do
                            create_club(params, count - 1)
                        else
                            nil
                        end
                end
            false ->
                errormsg = SchemaClub.getErrorMsg(changeset.error, %{})    #返回错误消息
                nil
        end
    end

    @doc """
    return club or nil
    """
    def find_club(invitecode) when is_bitstring(invitecode) do
        SchemaClub
        |> Ecto.Query.where(invitecode: ^invitecode)
        |> Repo.one
    end

    def find_club(id) when is_integer(id) do
        SchemaClub
        |> Repo.get(id)
    end
    
    def delete_club(invitecode) when is_bitstring(invitecode) do     
        case find_club(invitecode) do
            nil ->
                {:error, "没有这个社团，请认真核对！"}
            club ->
                case Repo.delete(club) do
                    {:ok, _ } ->
                        {:ok, "删除 #{club.name} 成功"}
                    {:error, _ } ->
                        {:error, "删除 #{club.name} 失败"}
                end

        end
    end
end